//
//  LLComposePhoto.m
//  Weibo
//
//  Created by 李灵斌 on 15-2-6.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "LLComposePhoto.h"
#define photoCount 9
#define margin 10
@interface LLComposePhoto ()
@property (nonatomic, weak) UIImageView *photoView;
@end

@implementation LLComposePhoto

- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (void)setup{
    
//    self.userInteractionEnabled = YES;
    for (int i = 0; i<photoCount; i++) {
        
        UIImageView *photoView = [[UIImageView alloc] init];
        photoView.contentMode = UIViewContentModeScaleAspectFill;
        photoView.clipsToBounds = YES;
        photoView.userInteractionEnabled = YES;
        [self addSubview:photoView];
        self.photoView = photoView;
        
        if (i == 0 ) {
            
            photoView.image = [UIImage imageNamed:@"compose_pic_add_highlighted"];
            photoView.tag = i;
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
            [photoView addGestureRecognizer:tap];
        }
    }
}

- (void)tapClick:(UIGestureRecognizer *)ges{
    
    if ([self.delegate respondsToSelector:@selector(composePhoto:)]) {
        
        [self.delegate composePhoto:self];
    }
}

- (void)layoutSubviews{
    
    int totalCol = 4;
    CGFloat photoWidth = (self.width - margin * (totalCol + 1)) / totalCol;
    CGFloat photoHeith = photoWidth;
    for (int i = 0; i<photoCount; i++) {
        UIImageView *photoView = self.subviews[i];
        int row = i / totalCol;
        int col = i % totalCol;
        
        photoView.width = photoWidth;
        photoView.height = photoHeith;
        
        photoView.x = margin + col * (margin + photoWidth);
        photoView.y = margin + row * (margin + photoHeith);
    }
}

- (void)setPhotos:(NSArray *)photos{
    
    _photos = photos;
    
    for (int i = 0; i<photos.count; i++) {
        
        UIImageView *photo = self.subviews[i];
//        if ((photo.tag == (i + 1))) {
//            
//            photo.image = [UIImage imageNamed:@"compose_pic_add_highlighted"];
//        }
        photo.image = photos[i];
        
    }
    
    if (photos.count == photoCount) return;
    UIImageView *image =  self.subviews[photos.count];
    image.image = [UIImage imageNamed:@"compose_pic_add_highlighted"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [image addGestureRecognizer:tap];
}

@end
